package com.lowcode.platform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lowcode.platform.common.PageResult;
import com.lowcode.platform.common.Result;
import com.lowcode.platform.entity.Permission;
import com.lowcode.platform.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 权限控制器
 */
@RestController
@RequestMapping("/api/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    /**
     * 分页查询权限
     */
    @GetMapping("/page")
    public Result<PageResult<Permission>> page(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String name) {
        
        Page<Permission> page = new Page<>(current, size);
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(name)) {
            wrapper.like(Permission::getName, name);
        }
        
        IPage<Permission> result = permissionService.page(page, wrapper);
        
        PageResult<Permission> pageResult = new PageResult<>(
                result.getTotal(),
                result.getRecords(),
                result.getCurrent(),
                result.getSize()
        );
        
        return Result.success(pageResult);
    }

    /**
     * 查询所有权限
     */
    @GetMapping("/list")
    public Result<List<Permission>> list() {
        List<Permission> permissions = permissionService.list();
        return Result.success(permissions);
    }

    /**
     * 权限树查询
     */
    @GetMapping("/tree")
    public Result<List<Permission>> tree() {
        List<Permission> permissions = permissionService.getPermissionTree();
        return Result.success(permissions);
    }

    /**
     * 根据ID查询权限
     */
    @GetMapping("/{id}")
    public Result<Permission> getById(@PathVariable Long id) {
        Permission permission = permissionService.getById(id);
        return Result.success(permission);
    }

    /**
     * 新增权限
     */
    @PostMapping
    public Result<Void> add(@RequestBody Permission permission) {
        permission.setStatus(1);
        permissionService.save(permission);
        return Result.success();
    }

    /**
     * 更新权限
     */
    @PutMapping
    public Result<Void> update(@RequestBody Permission permission) {
        permissionService.updateById(permission);
        return Result.success();
    }

    /**
     * 删除权限
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        permissionService.removeById(id);
        return Result.success();
    }
}
